# coding=utf-8
import datetime

from django.db import transaction
from rest_framework import generics
from rest_framework.views import APIView
from apps.member.activity.models import MemberActivity, Activity
from utils import response_error, response_ok
from utils.exceptions import CustomError
from utils.permission import IsMemberUser
from .filters import VoteActivityApplyFilter
from .models import VoteActivityApply, VoteActivity, MemberVoteRecord
from .serializers import VoteActivityApplyListSerializer, VoteActivityApplySerializer, VoteActivityApplyDetailSerializer


class VoteActivityApplyDetailView(APIView):
    permission_classes = [IsMemberUser, ]

    def get(self, request):
        try:
            activity_id = self.request.GET['activity_id']
            activity = Activity.get_instance_by_id(activity_id)
            number = self.request.GET['number']
            vote_activity_apply = VoteActivityApply.objects.filter(number=number,
                                                                   member_activity__activity=activity).first()
            if not vote_activity_apply:
                raise CustomError('未找到此编号报名信息')

            ser = VoteActivityApplyDetailSerializer(vote_activity_apply, context={'request': request})
            return response_ok(ser.data)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))


class VoteActivityApplyView(APIView):
    permission_classes = [IsMemberUser, ]

    def post(self, request):
        try:
            activity_id = request.data['activity_id']
            activity = Activity.get_instance_by_id(activity_id)
            member = request.user.member
            if activity.is_apply_activity(member):
                raise CustomError('已经报名给此活动。')

            vote_apply = request.data
            vote_apply['number'] = MemberActivity.objects.filter(activity=activity).count() + 1
            with transaction.atomic():
                member_activity = MemberActivity.objects.create(member=member, activity=activity)
                vote_apply_ser = VoteActivityApplySerializer(data=vote_apply)
                if vote_apply_ser.is_valid(raise_exception=True):
                    vote_apply = vote_apply_ser.save(member_activity=member_activity)
                    return response_ok(vote_apply.number)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))


class VoteActivityView(APIView):
    '''帮投票'''
    permission_classes = [IsMemberUser, ]

    def post(self, request):
        try:
            number = request.data['number']
            member = request.user.member

            activity_id = request.data['activity_id']
            activity = Activity.get_instance_by_id(activity_id)

            vote_activity_apply = VoteActivityApply.objects.filter(number=number,
                                                                   member_activity__activity=activity).first()
            if vote_activity_apply.member_activity.status == MemberActivity.FINISH:
                raise CustomError('活动已经结束')

            # 找到当前的投票活动
            activity = vote_activity_apply.member_activity.activity
            vote_activity = VoteActivity.objects.filter(activity=activity).first()

            # 判断投票次数
            if vote_activity.vote_way == VoteActivity.EVERYDAY:
                # 每天几次
                today = datetime.date.today()  # 2020-10-24
                # 查询用户当天投票次数
                vote_count = MemberVoteRecord.objects.filter(create_time__gte=today, member=member,
                                                             vote_activity=vote_activity).count()
                if vote_count >= vote_activity.vote_time:
                    raise CustomError('当前活动的每个用户每天可投票次数为{0},您当天的投票次数已经用完。'.format(vote_activity.vote_time))

            elif vote_activity.vote_way == VoteActivity.TOTAL:
                # 一共几次
                vote_count = MemberVoteRecord.objects.filter(member=member, vote_activity=vote_activity).count()
                if vote_count >= vote_activity.vote_time:
                    raise CustomError('当前活动的每个用户一共可投票次数为{0},您的投票次数已经用完。'.format(vote_activity.vote_time))

            with transaction.atomic():
                # 投票
                vote_activity_apply.count += 1
                vote_activity_apply.save()

                vote_activity.total_vote_count += 1
                vote_activity.save()
                # 记录投票
                MemberVoteRecord.objects.create(vote_activity=vote_activity, member=member)
                return response_ok()

        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))


class VoteActivityApplyListView(generics.ListAPIView):
    # 投票报名列表
    queryset = VoteActivityApply.objects.filter()
    serializer_class = VoteActivityApplyListSerializer

    def filter_queryset(self, queryset):
        # print(self.request.GET)
        f = VoteActivityApplyFilter(self.request.GET, queryset=queryset)
        return f.qs


class VoteActivityApplyTop20View(APIView):

    def get(self, request):
        try:
            top = int(self.request.GET['top'])
            activity_id = self.request.GET['activity_id']
            activity = Activity.get_instance_by_id(activity_id)
            activity_vote_apply = VoteActivityApply.objects.filter(member_activity__activity=activity)[:top]
            return response_ok(VoteActivityApplyListSerializer(activity_vote_apply, many=True).data)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
